<?php

namespace App\Http\Controllers\Admin\Content;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Models\Content\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends AdminController
{
    public function data()
    {
        $list = Category::query()->select(['id', 'sort', 'parent_id as parentId', 'name', 'status', 'created_at', 'updated_at'])
            ->orderByDesc('id')->get()->toArray();
        return $this->succeed($list);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required','max:50'],
        ]);
        $data = $request->only(['sort', 'parentId', 'name', 'status']);
        DB::beginTransaction();
        try {
            $model = Category::query()->create([
                'sort' => (int)$data["sort"],
                'parent_id' => (int)$data["parentId"],
                'name' => $data["name"],
                'status' => (int)$data["status"]
            ]);
            $this->createSyslog('添加了一条栏目记录', $data, $model);
            DB::commit();
            $item = $model->toArray();
            return $this->succeed([
                'id' => $item['id'],
                'created_at' => $item['created_at'],
                'updated_at' => $item['updated_at']
            ]);
        } catch (\Exception) {
            DB::rollBack();
        }
        return $this->fail();
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => ['required','max:50'],
        ]);
        $model = Category::query()->findOrFail($id);
        $data = $request->only(['sort', 'parentId', 'name', 'status']);
        DB::transaction(function () use ($model, $data) {
            $model->update([
                'sort' => (int)$data["sort"],
                'parent_id' => (int)$data["parentId"],
                'name' => $data["name"],
                'status' => (int)$data["status"]
            ]);
            $this->createSyslog('更新了一条栏目记录', $data, $model);
        });
        return $this->succeed();
    }

    public function destroy(Request $request)
    {
        $request->validate([
            'ids' => ['required','array','max:'.static::QUERY_LIMIT]
        ]);
        $ids = $request->get('ids');
        $rows = Category::query()->select('id')->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->withCount(['children', 'articles' => function ($query) {
            $query->withTrashed();
        }])->get();
        abort_if($rows->isEmpty(), ResponseEnum::DELETE_NOT_EXIST_ERROR);
        DB::transaction(function () use ($rows) {
            foreach ($rows as $row) {
                abort_if($row->children_count > 0, ResponseEnum::HTTP_ERROR, '存在子栏目，不能删除');
                abort_if($row->articles_count > 0, ResponseEnum::HTTP_ERROR, '存在文章，不能删除');
                $row->delete();
                $this->createSyslog('删除了一条栏目记录', [], $row);
            }
        });
        return $this->succeed();
    }
}
